package models.weixin.amount;

import enums.GoodsType;
import jodd.bean.BeanCopy;
import models.constants.DeletedStatus;
import models.weixin.WebUser;
import play.db.jpa.Model;

import javax.persistence.*;
import java.util.Date;
import java.util.List;

/**
 * 微信用户 设置为商户身份时 需要设置商户的信息 比如 超市名称 联系人 联系电话 授权码 等
 * Created by shancheng on 16-6-17.
 */
@Entity
@Table(name = "web_user_accounts")
public class WebUserAccount extends Model {

    private static final long serialVersionUID = 28910993422181221L;

    /**
     * 微信用户名称
     */
    @JoinColumn(name = "web_user_id")
    @ManyToOne
    public WebUser webUser;


    /**
     * 订单来源
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "goods_type")
    public GoodsType goodsType;

    /**
     * 可用金额
     */
    @Column(name = "amount")
    public Double amount = 0.00;

    /**
     * 支付密码
     */
    @Column(name = "password")
    public String password;


    /**
     * 用户注册时间
     */
    @Column(name = "created_at")
    public Date createAt;

    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    @Column(name = "deleted")
    public DeletedStatus deleted = DeletedStatus.UN_DELETED;

    public WebUserAccount() {
        super();
    }

    public WebUserAccount(WebUser webUser , Double amount) {
        this.webUser = webUser;
        this.amount = amount;
        this.createAt = new Date();
        this.deleted = DeletedStatus.UN_DELETED;
    }

    public WebUserAccount(WebUser webUser , Double amount , GoodsType goodsType) {
        this.webUser = webUser;
        this.amount = amount;
        this.goodsType = goodsType;
        this.createAt = new Date();
        this.deleted = DeletedStatus.UN_DELETED;
    }


    public WebUserAccount(WebUser webUser , Double amount , String password) {
        this.webUser = webUser;
        this.amount = amount;
        this.password = password;
        this.createAt = new Date();
        this.deleted = DeletedStatus.UN_DELETED;
    }


    /**
     * 按weixinUser值更新指定ID的WeixinUser.
     */
    public static void update(Long id, WebUserAccount webUserMerchant) {
        WebUserAccount oldEntity = WebUserAccount.findById(id);
        BeanCopy.beans(webUserMerchant, oldEntity).ignoreNulls(true).copy();
        oldEntity.save();
    }

    public static WebUserAccount findByWebUser(WebUser webUser) {
        return WebUserAccount.find("deleted = ? and webUser = ?" , DeletedStatus.UN_DELETED , webUser).first();
    }

    public static List<WebUserAccount> findAllByWebUser(WebUser webUser) {
        return WebUserAccount.find("deleted = ? and webUser = ?" , DeletedStatus.UN_DELETED , webUser).fetch();
    }

    public static WebUserAccount findByWebUserAndGoodsType(WebUser webUser , GoodsType goodsType) {
        return WebUserAccount.find("deleted = ? and webUser = ? and goodsType = ?" , DeletedStatus.UN_DELETED , webUser , goodsType).first();
    }

}
